#-*-coding:utf-8
import re
import sys
import os.path
import logging


class Translate() :
    """匹配javap输出的字符串，并进行格式化后输出"""

    def __init__(self):
        self.fieldList = list()
        self.fieldDict = dict()

    def open(self, inputStream) :
        """打开一个文件或者是一个字符串"""
        if os.path.isfile(inputStream) :
            self.file = open(inputStream, "r")
            if self.file:
                lines = self.file.readlines()
                s = ' '.join(lines)
                s.replace('\n', '')
                s.replace('\r', '')
                self.originStr = s
                return True
        elif isinstance("", str) :
            self.originStr = inputStream.replace('\n', '').replace('\r','')
            return True

        return False

    def setClassPath(self, classPath):
        self.classPath = classPath

    def setFileName(self, fileName):
        self.fileName = fileName
        self.className = self.fileName.split('.')[-1]
        logging.debug(self.className)

    def setOutPath(self, outPath):
        self.outPath = outPath

    def translate(self):
        """使用javap命令获得class信息，并解析输出.h和.cpp文件"""
        import subprocess
        args = ['javap','-s', '-classpath']
        args.append(self.classPath)
        args.append(self.fileName)
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (out, err) = p.communicate()
        logging.debug(out)
        self._match(out)

    def _match(self, javapOut):
        if javapOut is not None and isinstance(javapOut, str):
            # getfilelist and getfiledict
            pattern = re.compile(r"public\s(?!static)(?:\w*\.)*([\w*\[\]]*\s(?P<fieldName>\w*);)"\
                                 "[\s\n\r]*(?:Signature|descriptor):\s([\[\w\/]*[;]?)", \
                                 re.M)
            match = pattern.findall(javapOut)
            if match:
                del self.fieldList[:]
                self.fieldDict.clear()
                for element in match:
                    (fieldStr, fieldName, signature) = element
                    self.fieldList.append(fieldStr)
                    self.fieldDict[fieldName] = signature
                logging.debug(self.fieldDict)
                logging.debug(self.fieldList)

            # get whole filename
            pattern = re.compile(r"\bclass\s([\w\.]*)\b")
            match = pattern.search(javapOut)
            if match:
                self.wholeClassName = match.group(1)
            import output
            o = output.OutPut(self.fieldList, self.fieldDict, self.wholeClassName, self.outPath)
            o.output()
